import React from "react";

import PageContent from '../../PageContent'

import { Link } from 'react-router-dom';

import { Popover, Input,Select,Button } from 'antd';

import { ajax ,showResultMessage,isNull,isNotNull,isEmpty,setStoreItem,getStoreItem} from '../../common';

import {UIDataTableView} from '../../uicomponents/UIDataComponentView';

import UIFormView from '../../uicomponents/UIFormView';

import UIIcon from '../../uicomponents/UIIcon';

import ChooseProductUIComponentPanel from './ChooseProductUIComponentPanel';

import { getUIList } from '../../uiConfig';

const Option = Select.Option;

/** 
 *产品UI表单管理
*/
export default class ProductUIPageManageApp extends React.Component {

	state = {
		pageSearchValues : getStoreItem('uiPageSearchValues',{}),
	}

	onPageSearchValueChange = (values) => {
		this.setState({pageSearchValues : values});
		setStoreItem('uiPageSearchValues',values);
	}

	render() {

        /**路由设置 */
		const pageContentMap = {
			'/': {
				text: '',
				icon: '',
				getComponent: (owner, props) => {
					return (<ProductUIPageListPanel {...props} 
						pageSearchValues={this.state.pageSearchValues} 
						onPageSearchValueChange={this.onPageSearchValueChange}
						key="uiPageList" 
						
						/>
						);
				}
			},
			'/editUIPageParams': {
				text: '编辑页面参数',
				icon: 'edit',
				getComponent: (owner, props) => {
					return (<EditProductUIPageParamListPanel {...props} key="editUIPageParams" />);
				}
			},
        }

		return (
			<PageContent {...this.props} pageInstance={this} contentMap={pageContentMap}>
				
			</PageContent>
		);
	}
}

/**
 * 产品页面列表
 */
class ProductUIPageListPanel extends React.Component{

    constructor(props) {
		super(props);
		this.state = {
            formTitle: '',
		}
    }

	actionHandler = (actionEvent) => {

		const { selectPageIds, pageListRef, pageFormRef } = this;

		return {
			refresh : () => {
				pageListRef.loadData();
			},
			addNew : () => {
				this.setState({ formTitle: '新增产品UI页面'});
				setTimeout(() => {
					pageFormRef.openModal(() => {
						const initParams = getStoreItem('uiPageSearchValues',{});
						if(isNotNull(initParams['domainId'])){
							pageFormRef.setFormData({domainId : initParams['domainId']});
						}
					});
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑产品U页面' });
				setTimeout(() => {
					pageFormRef.openModal(() => {
						pageFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (isNull(actionEvent.params) !== true) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectPageIds;
				}
				
				ajax('PRODUCT/UI/ProductUIPage/batchDelete', { ids: selectedIds }, (data) => {
					pageListRef.loadData();
				});
			},
			doSave : () => {
				pageFormRef.getFormData((formData) => {

					ajax('PRODUCT/UI/ProductUIPage/save', formData, (data) => {
						pageFormRef.closeModal();
						pageListRef.loadData();
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {

		const pageProps = {
            ref: (inst) => { this.pageListRef = inst },
			history : this.props.history,
			title : "UI页面",
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIPageListActionGroup',
			rowActionGroupId: 'productUIPageRowActionGroup',
			tableConfigId: 'productUIPageTable',
			dataUrl: 'PRODUCT/UI/ProductUIPage/query',
			selectMode: 'multi',
			searchFormId: 'productUIPageSearchForm',
			initSearchValues : this.props.pageSearchValues,
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectPageIds = selectRowKeys;
				}
            ,
            onSearchData : (changedValues) => {
				
				if(this.props.onPageSearchValueChange){
					this.props.onPageSearchValueChange(changedValues)
				}
			}
		};

		const pageFormProps = {
			ref: (inst) => { this.pageFormRef = inst },
			formConfigId: 'productUIPageForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView {...pageProps}>
				<UIFormView {...pageFormProps} />
			</UIDataTableView>
		);
	}

}

/**
 * 编辑页面参数
 */
class EditProductUIPageParamListPanel extends React.Component{

    constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			pageTitle : '',
			pageParam : null,
		}
	}
	
	componentDidMount(){
		this.page = this.props.location.state;
		this.setState({pageTitle : '编辑[' + this.page.pageName +   ']页面参数'});
		this.loadPageParams(this.page.id);
	}

    loadPageParams = (pageId) => {
		
        this.pageParamListRef.loadData({pageId : pageId});
    }

    actionHandler = (actionEvent) => {
		const {pageParamFormRef} = this;
        return {
            refresh : () => {
                this.loadPageParams(this.page.id);
            },
            doEdit : () => {
				this.pageParam = actionEvent.params;
                pageParamFormRef.openModal(() => {
					pageParamFormRef.setFormData(actionEvent.params,(formField,formData,filedsData) => {
						if(formField.id === 'pageParamValue' && formData.paramInputType.indexOf('UI') !== -1){
							filedsData[formField.id] = {
								pageParamId : formData.pageParamValueId,
								pageParamValue : formData.pageParamValue,
							};
						}
					});
                });
			},
			doSave : () => {
				pageParamFormRef.getFormData((formData) => {
					if(formData.paramInputType.indexOf('UI') !== -1){
						const pageParamValue = formData.pageParamValue;
						formData.pageParamValue = pageParamValue.pageParamValue;
						formData.pageParamValueId = pageParamValue.pageParamId;
					}
					
					ajax('PRODUCT/UI/ProductUIPageParam/save',formData,(data) => {
						pageParamFormRef.closeModal();
						this.loadPageParams(this.page.id);
					})
				});
			},
            synchPageParamters : () => {
                ajax('PRODUCT/UI/ProductUIPageParam/synchPageParamters',{pageId : this.page.id},(data) => {
                    this.loadPageParams(this.page.id);
                });
            }
        };
	}

	renderUIPageParamValueField = (formField,fieldDecoratorOptions,itemLayout) => {
		
		const {pageParam} = this;

		if(pageParam.paramInputType === "UserInput"){
			return (<Input type="text" readOnly={formField.readOnly === true} placeholder={formField.tipInfo} />);
		}
		else if(pageParam.paramInputType.indexOf('UI') !== -1){
			return (
				<ChooseUIComponentInput uiCompoment={pageParam.paramInputType} defaultDomianId={this.page.domainId}/>
			);
		}
		else{
			const list = getUIList(pageParam.paramInputType);
			const optionItems = list.listData.map((data) => {
				return (<Option key={data.data} value={data.data}>{isEmpty(data.icon) === false ? <UIIcon icon={data.icon} /> : ''}{data.label}</Option>);
			});
			return (
                <Select
                    allowClear={formField.allowNull !== false}
                    getPopupContainer={trigger => trigger.parentNode}
                    placeholder={formField.tipInfo}
                >
                    {
						optionItems
					}
                </Select>
            );
		}
		
	}

    render() {
        const tableProps = {
            bordered : false,
            title : this.state.pageTitle,
            extra : (<Link to="/">返回</Link>), 
			ref: (inst) => { this.pageParamListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIPageParamListActionGroup',
			rowActionGroupId: 'productUIPageParamRowActionGroup',
			tableConfigId: 'productUIPageParamTable',
			dataUrl: 'PRODUCT/UI/ProductUIPageParam/query',
			selectMode: 'multi',
			autoLoad: false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		const formProps = {
			ref: (inst) => { this.pageParamFormRef = inst },
			formConfigId: 'productUIPageParamForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: '编辑参数',
			fieldRender : this.renderUIPageParamValueField,
		};

		return (
			<UIDataTableView {...tableProps}>
				<UIFormView {...formProps} />
			</UIDataTableView>
		);
    }
}

/**
 * 选择UI组件输入框
 */
class ChooseUIComponentInput extends React.Component {
	static getDerivedStateFromProps(nextProps) {
	  // Should be a controlled component.
	  if ('value' in nextProps) {
		return {
		  ...(nextProps.value || {}),
		};
	  }
	  return null;
	}
  
	constructor(props) {
	  super(props);
  
	  const value = props.value || {};
	  this.state = {
		pageParamValue: value.pageParamValue || '',
		pageParamId: value.pageParamValueId || '0',
	  };
	}
  
	onChooseUIComponent = (value) => {
		//console.log(value);
		if (!('value' in this.props)) {
			this.setState({ pageParamValue: value.value,pageParamId: value.id});
	  	}
	  	this.triggerChange({ pageParamValue: value.value,pageParamId: value.id});
	}
  
	triggerChange = (changedValue) => {
	  // Should provide an event to pass value to Form.
	  const onChange = this.props.onChange;
	  if (onChange) {
		onChange(Object.assign({}, this.state, changedValue));
	  }
	}
  
	render() {
	  const { size } = this.props;
	  const state = this.state;
	  return (
		<span>
		  <Input
			type="text"
			size={size}
			value={state.pageParamValue}
			readOnly={true}
			style={{ width: '75%', marginRight: '3%' }}
		  />
		  <Button type="danger" icon="close" style={{ width: '11%' }} onClick={ (e) => {this.onChooseUIComponent({ value: '',id: 0});}  }/>
		<Popover
			placement="bottomLeft"
			trigger="click"
			content={
				<ChooseProductUIComponentPanel 
					uiCompoment={this.props.uiCompoment} 
					onChooseUIComponent={this.onChooseUIComponent} 
					defaultDomianId={this.props.defaultDomianId}
				/>
			}
			title={'选择UI组件'}
		>
			<Button type="primary" icon="search" style={{ width: '11%' }}/>
		</Popover>
		</span>
	  );
	}
  }
  

